package com.devicemantra.coordinate.auth;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.datanucleus.store.Extent;

import com.devicemantra.coordinate.dataobjects.CLoginInfo;
import com.devicemantra.coordinate.dataobjects.CUserFactory;
import com.devicemantra.coordinate.ds.tests.PMF;

@SuppressWarnings("serial")
public class CopyOfLogin extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
   {
		String lLoginName = (String) req.getParameter("login_name");
		String lPassword = (String) req.getParameter("password");
		System.out.println("LoginName is " + lLoginName + " Password is " + lPassword);
		CLoginInfo lLoginInfo = CUserFactory.getUserLoginInfo(lLoginName);
		
		if(lLoginInfo == null)
		{
			System.out.println("User does not exist");
			req.getSession().setAttribute("login_err_mesg", "Login failed - username and password do not match");
			try {
				req.getRequestDispatcher("login.jsp").forward(req,resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}
		
		String lForwardUrl = "";
		if( true == CUserFactory.checkPasswordForUsername(lLoginName, lPassword))
		{
			/* Login success - let us set the user for the session  */
			req.getSession().setAttribute("user", lLoginInfo.getUserName());
			if( lLoginInfo.getUserName().equals("SUPER_ADMIN"))
			{
				lForwardUrl = "interface.jsp";
			}
			else
			{
				lForwardUrl = "/modules/department/interface.jsp";
				
			}
			System.out.println("Forwarding to url - " + lForwardUrl);
		}
		else /* Login failed */
		{
			System.out.println("User EXISTS but login failed ");
			req.getSession().setAttribute("login_err_mesg", "Login failed - username and password do not match");
			lForwardUrl = "login.jsp";
		}
		
		try {
			req.getRequestDispatcher(lForwardUrl).forward(req,resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//resp.getOutputStream().print("login name was " + lLoginName);
		
		
   }
}
